package org.kokia;

import io.netty.bootstrap.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;

/**
 * Hello world!
 *
 */
public class EchoServer {
    private final int port;

    public EchoServer (int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(group).channel(NioSctpServerChannel.class).localAddress(port)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline()
                                    .addLast(new EchoServerHandler());
                        }
                    });

            ChannelFuture future = bootstrap
                    .bind()
                    .sync();
            System.out.println(EchoServer.class.getName() + "started and listen on “" + future.channel().localAddress());
            group.shutdownGracefully().sync();
        } finally {
            group.shutdownGracefully()
                    .sync();
        }
    }

    public static void main(String[] args ) throws Exception {
        new EchoServer(65535).start();
        System.out.println( "Hello World!" );
    }
}
